<template>
  <div class="login">
    <!-- 表单校验1 在form标签添加rules属性，添加校验规则，通过prop监听要校验的数据 -->
    <el-form :model="loginFrom" class="container" :rules='myrules' ref='loginFrom'>
      <el-form-item>
        <div class='avatar'>
          <img src="../assets/avatar.jpg" alt="">
        </div>
      </el-form-item>
      <el-form-item prop="username">
        <el-input v-model="loginFrom.username" prefix-icon='myicon myicon-user'></el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input type="password" v-model="loginFrom.password" prefix-icon='myicon myicon-key'></el-input>
      </el-form-item>
      <el-form-item>
        <!-- 点击的时候将ref的值作为参数传递到函数submitLogin中去，注意加上引号 -->
        <el-button type="primary login-btn" @click="submitLogin('loginFrom')">登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import { postLogin } from '../api'
export default {
  data () {
    return {
      loginFrom: {
        username: 'admin',
        password: '123456'
      },
      // 表单校验1.2 自己书写校验规则
      myrules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
      }
    }
  },
  methods: {
    submitLogin (refval) {
      // 发请求之前，先用element-ui里面封装的validate()对表单进行校验
      this.$refs[refval].validate(isPass => {
        if (isPass) {
          postLogin({ username: this.loginFrom.username, password: this.loginFrom.password })
            .then(res => {
              console.log(res)
              if (res.meta.status === 200) {
                // 将服务器返回的token保存到本地
                localStorage.setItem('mytoken', res.data.token)
                //  将服务器返回的用户名保存到本地
                localStorage.setItem('username', res.data.username)
                // 成功跳转到首页
                this.$router.push({ name: 'home' })
              } else {
                // 失败就弹出错误提示信息
                this.$message.error(res.meta.msg)
              }
            })
        } else {
          this.$message.warning('请正确填写表单')
          return false
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
  .login {
    position: fixed;
    width: 100%;
    height: 100%;
    background:url('../assets/冰公主 士兵 白鸽和圣堂 鬼刀4k原画壁纸_彼岸图网.jpg');
    background-size: 100% 100%;
    .container {
      position: absolute;
      left: 0;
      right: 0;
      width: 400px;
      padding: 0px 40px 15px 40px;
      margin: 200px auto;
      background: white;
      .avatar {
        position: relative;
        left: 50%;
        width: 120px;
        height: 120px;
        margin-left: -60px;
        margin-top: -60px;
        box-sizing: border-box;
        border-radius: 50%;
        border: 10px solid #fff;
        box-shadow: 0 1px 5px #ccc;
        overflow: hidden;
      }
      .login-btn {
        width: 100%;
      }
    }
  }
</style>
